<% // Copyright 2008 Carnegie Mellon University
// Licensed under the Apache License, Version 2.0 (the "License"); 
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//  
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, 
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License. %>
<%@page language="java" contentType="text/html; charset=UTF-8" %>
<%@page pageEncoding="UTF-8" %>
<%@page import="edu.cmu.lti.*"%>
<%@page import="edu.cmu.lti.sepia.data.db.SQL"%>
<%@page import="edu.cmu.lti.sepia.data.resource.ResourceManager"%>
<%@page import="edu.cmu.lti.sepia.task.retrieval.*"%>
<%@page import="edu.cmu.lti.sepia.task.retrieval.indri.*"%>
<%@page import="edu.cmu.lti.sepia.util.ExceptionUtil"%>
<%@page import="edu.cmu.lti.sepia.util.Logger"%>

<%
request.setCharacterEncoding("UTF-8");
response.setHeader("progma", "no-cache");
response.setHeader("Cache-Control", "no-cache");

String lang = (String)session.getAttribute("trgLang");

String taskNameShort = (String)session.getAttribute("taskNameShort");

boolean isStandalone = request.getParameter("isStandalone")!=null && ((String)request.getParameter("isStandalone")).length()>0;

String collection = request.getParameter("collection");
if (collection == null) collection = "";

String query = request.getParameter("indriQuery");
if (query!=null && query.length()>0 && query.charAt(0)==63) { // '?' is 63 indicating encoding failure
  query = new String(query.getBytes("ISO8859_1"), "UTF8");
}
//query = (request.getParameter("indriQuery")!=null)?new String(request.getParameter("indriQuery").getBytes("ISO_8859_1"), "UTF-8"):"";
int maxDocs = (request.getParameter("maxDocs")!=null)?Integer.parseInt( request.getParameter("maxDocs") ):0;

String errorMessage = "";
Retriever r = null;
try {
  r = Retriever.getInstance( taskNameShort );
  //r.init(); // Update indri home -> done in 
} catch (Exception e) {
  errorMessage = "ERROR: make sure indri home and indri corpus are properly configured."+
                 "<pre>"+ExceptionUtil.exceptionToString(e)+"</pre>";
}
%>
<!-- 
new String(request.getParameter(key).getBytes(enc1),enc2);
<%=(request.getParameter("indriQuery")!=null)?new String(request.getParameter("indriQuery").getBytes("ISO_8859_1"), "UTF-8"):""%>

request.getParameter(key);
<%=request.getParameter("indriQuery")%>

Encoding-detected query:
<%=query %>
 -->

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Indri Web Interface</title>

<link rel="stylesheet" type="text/css" href="../css/search.css" />
<link rel="stylesheet" type="text/css" href="../css/common.css" />
<link rel="stylesheet" type="text/css" href="../css/external/redmond/jquery-ui-1.8.12.custom.css" />

<script type="text/javascript" src="../js/external/jquery.js"></script>  
<script type="text/javascript"><!-- jQuery.noConflict(); //--></script>
<script type="text/javascript" src="../js/external/jquery.rangy-core.js"></script>
<script type="text/javascript" src="../js/external/jquery-ui-1.8.12.custom.min.js"></script>
<script type="text/javascript" src="../js/external/prototype.js"></script>
<script type="text/javascript" src="../js/resources.js.jsp"></script>
<script type="text/javascript" src="../js/shared.js"></script>
<script type="text/javascript" src="../js/selection.js"></script>
<script type="text/javascript" src="../js/search.js"></script>
<script type="text/javascript">
function showStats() {
  var stats = '';
<%
  if ( r!=null ) {
    String dump = r.dumpInfo();
    String[] lines = dump.split("\\n");
    for ( String line : lines ) {
      out.println("  stats += '"+line+"<br>';");
    }
  }
%>
  $('result_area').innerHTML = stats;
}

</script>

</head>
<body onload="loadMessages(lang)<%=isStandalone?";loadHeaderSubSub(lang);":"" %>">

<%
if (isStandalone) {
  out.println("<!-- HEADER --><div id=\"header\"></div><br>");
}
%>

<!-- 
<div style="float:right;align:right;">
<input class="msg_ir_query2" type="button" value="INDRI HELP" onclick="window.open('http://www.lemurproject.org/lemur/IndriQueryLanguage.php', 'help'); return false"><br>
<input class="msg_ir_stats" type="button" value="CORPUS STATS" onclick="showStats()" >
</div>
-->
<!-- <h2><span id="ir"></span><img src="http://boston.lti.cs.cmu.edu/lti-search/lemur_l_24.gif" /></h2> -->

<form action="indri.jsp" method="post">

<table border="0" cellpadding="3" cellspacing="1">
<tr><td style="background-color:#cccccc">1. <span id="msg_ir_query1"></span></td>
<td style="background-color:#cccccc">2. <span id="msg_ir_query3"></span></td></tr>
<tr><td style="background-color:#efefef">
<input type="text" name="querywords" id="querywords" onChange="enteredWord('OR')" onFocus="enteringWord()"
 style="width:<%="CS".equals(lang.toUpperCase())?185:285%>px" class="inputbox">
</td><td style="background-color:#efefef" nowrap>
&nbsp;&nbsp;
<input id="ir_convert_and" class="msg_ir_convert_and" type="button" value=" AND " onclick="enteredWord('AND')">
&nbsp;&nbsp;
<input id="ir_convert_or" class="msg_ir_convert_or" type="button" value=" OR " onclick="enteredWord('OR')">
&nbsp;&nbsp;
<input id="ir_convert_phrase" class="msg_ir_convert_phrase" type="button" value=" PHRASE " onclick="enteredWord('PHRASE')">
</td></tr>
<tr><td colspan="2" style="background-color:#cccccc">
3. <span id="msg_ir_query2"></span>
</td></tr>
<tr><td colspan="2" style="background-color:#efefef">
<textarea rows="5" cols="55" name="indriQuery" id="indriQuery" 
 onChange="postprocess()" class="inputbox" style="width:98%"><%=((query!=null)?query:"")%></textarea>
</td></tr>
<tr><td colspan="2" align="right" style="background-color:#efefef">
<span id="msg_ir_num_result"></span>&nbsp;&nbsp;
<input type="text" name="maxDocs" id="maxDocs" value="<%=(maxDocs>0?maxDocs:100)%>" size="3" class="inputbox"/>
&nbsp;&nbsp;&nbsp;&nbsp;
<input class="msg_ir_search" type="submit" value="SEARCH" />
<input type="hidden" name="isStandalone" id="isStandalone" value="<%=isStandalone?"true":""%>">
</table>
</form>
<a href="http://www.lemurproject.org/lemur/IndriQueryLanguage.php" target="_blank" id="msg_ir_query2"></a>
&nbsp;&nbsp;&nbsp;
<a href="javascript:void(0)" onclick="showStats()" id="msg_ir_stats"></a>  


<hr size="1">

<div id="result_area">
<!-- IF THERE ARE RESULTS -->
<%   
    out.println(errorMessage);
  
    if (r!=null) {
      String report = r.validationReport;
      if ( report.length()>0 && !ResourceManager.debugMode ) {
        out.println( "<em>ERROR</em><br>" );
        out.println( report );
      } else if ( query == null || query.equals( "" ) ) {
          //out.print( "Query must not be empty." );
      } else {
        try {
          String indices = (String)session.getAttribute("indices");
          long t0 = System.currentTimeMillis();
          ParsedDocument[] pds = r.retrieve( query, maxDocs );
          long t1 = System.currentTimeMillis();
          String[] queryTerms = IndriUtil.getQueryTerms(query);
          
          SQL sql = new SQL();
          Logger.log(sql, request.getSession(), "SEARCH", query );
          sql.close();
          
          String speed = (double)(t1-t0)/1000D+"";
          speed = speed.substring( 0, Math.min(4,speed.length()) );
            StringBuilder sb = new StringBuilder();
            if (pds.length>0){
              sb.append( "<div align=\"right\">Retrieved "+pds.length +" document"+(pds.length>1?"s":"")+" ("+speed+" sec).</div>" );
              sb.append( "<input type=\"button\" value=\"&nbsp;Open/Close All Docs&nbsp;\" onclick=\"javascript:showHideAllDocs()\" style=\"margin-bottom:10px\">\n" );
              sb.append( "<br>" );
            }
            sb.append( "<table width=100% border=0 cellpadding=5 cellspacing=0>\n" );
            for ( int i = 0; i < pds.length; i++ ) {
              String document = r.getDocument(lang, pds[i]);
              String snippet = r.getSnippet(document, queryTerms);
              String content = r.getHighlightedDoc(document, queryTerms);
              sb.append( "<tr class=\"snippet\"><td valign=\"top\" width=\"50\">" );
              sb.append( "<input type=\"button\" value=\"&nbsp;"+(i+1)+"&nbsp;\" onclick=\"javascript:showHideDoc("+i+")\">" );
              sb.append( "</td><td valign=\"top\">\n" ); 
              sb.append( "<div id=\"snippet"+i+"\" style=\"overflow:hidden;height:1.5em;width:95%;\">" );
              sb.append( snippet );
              sb.append( "</div>\n" );
              sb.append( "<pre id=\"doc"+i+"\" class=\"doc\" style=\"display:none\">" );      
              sb.append( content );
              sb.append( "</pre>\n" );
              sb.append( "</td></tr>\n" );
            }
            sb.append( "</table>\n" );
      
            if (pds.length>0){
              sb.append( "<br><input type=\"button\" value=\"&nbsp;Open/Close All Docs&nbsp;\" onclick=\"javascript:showHideAllDocs()\">\n" );
            } else {
              sb.append( "No result matched the query." );
            }
            
          out.println( sb.toString() );
          
        } catch ( Exception e ) {
          out.println( "No result matched the query." );
          out.println( "<!--"+e.getMessage()+"-->" );
        }
      }
    }
%>
</div>

<!-- for right clicking -->
<div id="command_list" class="ui-corner-all">
<ul id="command_list_ul">
<!-- Something like this will be automatically generated by search.js -->
<!-- <li id="command_copy"><a href="javascript:void(0);">Add</a></li> -->
</ul>
</div>

</body>
</html>